const innerAudioContext = wx.createInnerAudioContext() //播放录音
var util = require('../../util.js');
const app = getApp()

Page({
  data: {
    isShow: false,
    id: '', //拿到的留言信息ID
    kind: '',
    contentData: [],
    modalName: '',
    start_run: false,
    show_money_state: true, //还未领取红包
    play_inerval: '',
    show_login: false,
    share: false,
    suiji: false
  },
  onLoad: function (e) {
    app.createAdv()
    wx.showLoading({
      title: '数据获取中...',
    })
    this.data.kind = e.kind
    this.data.idx = e.idx

    if (!e.id) { //预览
      const contentArr = wx.getStorageSync('contentArr')
      const user_info = wx.getStorageSync('user_info')
      contentArr.red_message = contentArr.red_message || '毕业快乐！'
      wx.hideLoading()
      this.setData({
        show_preview: true,
        isShow: true,
        contentData: contentArr,
        from_id: user_info.id, //发件人
        member_id: contentArr.member_id, //接收人
        from_headimg: user_info.headimgurl,
        taping: contentArr.taping,
        taping_url: contentArr.taping,
        taping_time: contentArr.taping_time, // 录音的秒数
      })
      var min = Math.floor(this.data.taping_time / 60) % 60
      var sec = this.data.taping_time % 60
      this.setData({
        video_time_min: ('0' + min + ':' + (sec < 10 ? '0' + sec : sec))
      })
    } else {
      this.data.id = e.id
      if (this.data.kind == 'send') {
        this.data.show_send = true
        this.data.is_test=true
      }
      if (this.data.kind == 'receive') {
        // 收到的留言
        this.data.suiji = e.suiji
        this.data.show_send = false
        this.data.is_test=false
        this.data.show_login=(wx.getStorageSync('user_info')?false:true)
      }
      // 从分享页面中查看
      if (this.data.kind == 'check') {
        this.data.show_send = true
        this.data.show_check = true
        this.data.share = true
        this.data.is_test=false
      }
      this.getData(true)
    }
    this.setData({
      show_check: this.data.show_check,
      show_send: this.data.show_send,
      share: this.data.share,
      suiji: this.data.suiji,
      show_login:this.data.show_login,
    })
  },
  onShow: function () {
    app.showAdv()
  },
  getData: function (e) {
    var that = this
    var data = wx.getStorageSync('user_info')
    var member_id = (data ? data.id : 0)
    var url = 'Mailbox/indexs?id=' + that.data.id + '&member_id=' + member_id
    app.get_request(url).then(function (res) {
      var contentData = res.data.data.list[0]
      contentData.create_time = util.formatTimeTwo(contentData.create_time, 'Y/M/D')
      contentData.member_id = (data ? data.id : contentData.member_id)
      contentData.red_type= (data ? contentData.red_type : 0)
      if(contentData.from_id=='0000'){
        contentData.red_packet=(res.data.Redrecord?res.data.Redrecord.money:wx.getStorageSync('suiji'))
      }else{
        contentData.red_packet=(res.data.Redrecord?res.data.Redrecord.money: contentData.red_packet)
      }
      
      that.setData({
        letter_img: app.data.letter_img,
        contentData: contentData,
        taping_url: contentData.taping,
        taping_time: contentData.record_time,
        headimgurl:(that.data.is_test?contentData.senduserimg:contentData.headimgurl),
        name:(that.data.is_test?contentData.sendusername:contentData.from_name),

      })
      var min = Math.floor(that.data.taping_time / 60) % 60
      var sec = that.data.taping_time % 60
      that.setData({
        video_time_min: ('0' + min + ':' + (sec < 10 ? '0' + sec : sec))
      })
      if (that.data.taping_url) {
        if (e) {
          that.data.start_video = false
          setTimeout(() => {
            that.playVideo()
          }, 550);
        } else {
          that.stopVideo()
        }
      }
      that.setData({
        start_video: that.data.start_video,
        isShow: true,
      })
      wx.hideLoading()
    })
  },
  showModal(e) {
    this.stopVideo()
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  // 领取红包
  getMoney(e) {
    this.stopVideo()
    this.setData({
      modalName:'get_money'
    })
    var that = this
    var data = {
      id: that.data.id,
    }
    app.post_request('Mailbox/Receive', data).then(function (res) {
      if (res.data.status = '200') {
        // 添加红包数据
        that.postRedrecord()
        console.log("领取成功", res.data)
      } else {
        console.log("失败", res)
      }
    })
  },

  postRedrecord() {
    var that = this
    var data = {
      member_id: this.data.contentData.member_id,
      user_id: this.data.contentData.from_id,
      is_minus: 0, //领取
      money: this.data.contentData.red_packet,
    }
    app.post_request('Redrecord/add', data).then(function (res) {
      console.log("红包记录修改ok")
      that.getData()
    })
  },
  onGotUserInfo: function (e) { //授权登录
    var state = e.detail.errMsg
    var that = this
    if (state == 'getUserInfo:ok') {
      app.wx_loginTip()
      app.wx_login().then(function (result) {
        app.wx_getUserInfo().then(function (result) {
          var user_info = wx.getStorageSync('user_info')
          that.data.contentData.member_id=user_info.id
          that.setData({
            show_login: false,
            contentData:that.data.contentData,
          })
          that.getMoney()
          app.wx_loginOk()
        })
      })
    } else {
      console.log("取消授权")
    }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  // 查看图片
  previewImage: function (e) {
    this.stopVideo()
    var that = this
    var nowUrl = e.currentTarget.dataset.src;
    var imgUrls = that.data.contentData.photo
    //图片预览
    wx.previewImage({
      current: nowUrl, // 当前显示图片的http链接
      urls: imgUrls // 需要预览的图片http链接列表
    })
  },
  playVideo: function () {
    var that = this
    this.setData({
      start_video: !this.data.start_video,
      play_time_min: '00:00',
    })
    innerAudioContext.src = this.data.taping_url
    if (that.data.start_video) {
      innerAudioContext.play()
      that.data.play_inerval = null
      var time = 0
      that.data.play_inerval = setInterval(() => {
        time++
        if (time <= that.data.taping_time) {
          var min = Math.floor(time / 60) % 60
          var sec = time % 60
          that.setData({
            play_time_min: ('0' + min + ':' + (sec < 10 ? '0' + sec : sec))
          })
          if (time == that.data.taping_time) {
            console.log("播放时长到")
            clearInterval(that.data.play_inerval)
            innerAudioContext.stop()
            that.setData({
              start_video: false,
            })
          }
        }
      }, 1000);
    } else {
      // 停止播放
      var that = this
      clearInterval(this.data.play_inerval)
      console.log("点击了停止播放")
      innerAudioContext.stop()
      innerAudioContext.onStop((e) => {})
    }
  },
  moneyState: function () {
    this.setData({
      modalName: null,
      show_money_state: false
    })
  },
  // 设置私密/公开
  changeState(e) {
    this.stopVideo()
    var that = this
    var state = e.target.dataset.target
    that.setData({
      type: (state == 'secret' ? '12' : '0'),
    })
    var title = (state == 'secret' ? '确定要设为私密么？' : '确定要设为公开么？')
    wx.showModal({
      title: title,
      success(res) {
        if (res.confirm) {
          that.toChangeState()
        }
      }
    })
  },
  // 确定设置私密/公开
  toChangeState() {
    var that = this
    app.post_request('Mailbox/update', {
      "id": this.data.id,
      'type': this.data.type
    }).then(function (res) {
      wx.showToast({
        title: '修改成功',
        icon: 'success',
        duration: 2000,
        success(res) {
          that.getData()
          that.setData({

          })
        }
      })
    })
  },
  back: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  // del
  del() {
    this.stopVideo()
    var that = this
    wx.showModal({
      title: '确定要删除该留言？',
      success(res) {
        if (res.confirm) {
          that.toDel()
        }
      }
    })
  },
  toDel() {
    var that = this
    wx.request({
      method: 'post',
      url: 'https://classmate.lodidc.cn/api/Mailbox/del',
      data: {
        id: that.data.id
      },
      success(res) {
        if (res.data.status == '200') {
          app.wx_showSuccess("删除成功")
          setTimeout(() => {
            var pages = getCurrentPages()
            var data = pages[pages.length - 2].data
            var beforePage = pages[pages.length - 2]
            if (that.data.kind == 'send') {
              var sendDataList = data.sendDataList
              sendDataList.splice(that.data.idx, 1)
              beforePage.setData({
                sendDataList: sendDataList,
                sendIndex: (that.data.idx - 1) >= 0 ? (that.data.idx - 1) : 0,
              })
            } else {
              var receiveDataList = data.receiveDataList
              receiveDataList.splice(that.data.idx, 1)
              beforePage.setData({
                receiveDataList: receiveDataList,
                receiveIndex: (that.data.idx - 1) >= 0 ? (that.data.idx - 1) : 0,
              })
            }



            wx.navigateBack({
              delta: 1
            })
          }, 2000);
        }
      }
    })
  },
  stopVideo() {
    clearInterval(this.data.play_inerval)
    innerAudioContext.src = this.data.taping_url
    innerAudioContext.stop()
    innerAudioContext.onStop((e) => {})
    this.setData({
      start_video: false,
      play_time_min: '00:00'
    })
  },
  // preview
  // 发送
  Send(e) {
    var that = this
    var type = e.target.dataset.target
    // type=0--公开
    that.data.type = (type == "open" ? '0' : "1")
    // 如果有红包
    if (that.data.contentData.red_packet) {
      wx.showModal({
        title: '您有待发红包需要支付哦~',
        content: '支付后就可以发送啦',
        confirmText: '确定支付',
        success(res) {
          if (res.confirm) {
            that.toPay()
          }
        }
      })
    } else {
      // console.log("没有待发红包")
      that.toSend()
    }
  },

  toPay: function () {
    wx.showLoading({
      title: '支付调起中...',
      mask: true,
    })
    var that = this
    wx.request({
      method: 'post',
      url: 'https://classmate.lodidc.cn/api/Order/add',
      data: {
        total_fee: that.data.contentData.red_packet,
        // total_fee: 0.01,
        member_id: that.data.contentData.member_id,
      },
      success(res) {
        var order_id = res.data.order_id
        var amount = res.data.amount
        wx.login({
          success(res) {

            var code = res.code //存取第三方平台code到公用数据字段
            wx.request({
              method: 'post',
              url: 'https://classmate.lodidc.cn/api/Order/classpay',
              data: {
                code: code,
                order_id: order_id,
                amount: amount
              },
              success(res) {
                wx.hideLoading()
                wx.requestPayment({
                  appId: res.data.data.appId,
                  nonceStr: res.data.data.nonceStr, //随机字符串
                  package: res.data.data.package, //统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=***
                  paySign: res.data.data.paySign, //签名
                  signType: 'MD5', //签名算法
                  timeStamp: res.data.data.timestamp, //时间戳
                  success: function (res) {
                    that.toSend()
                  },
                  fail: function (res) {
                    // fail
                    console.log("pay.fail", res);
                  },
                })

              }
            })
          },
          fail: function (err) {
            console.log("app.login.fail", err);
          },
        })
      }
    })
  },

  toSend() {
    var that = this
    wx.showLoading({
      title: '发送中...',
    })
    return new Promise((resolve, reject) => {
      wx.request({
        method: 'post',
        url: 'https://classmate.lodidc.cn/api/Base/curlText',
        data: {
          content: that.data.contentData.message
        },
        success(res) {
          if (res.data.errcode != 87014) {
            wx.request({
              method: 'post',
              url: 'https://classmate.lodidc.cn/api/Mailbox/add',
              data: {
                // "member_id": '83895',
                // "from_id": '83870',
                "from_id": that.data.from_id,
                "member_id": that.data.contentData.member_id,
                'sendusername': that.data.contentData.sendusername,
                'senduserimg':that.data.contentData.senduserimg,
                'from_name': that.data.contentData.from_name,
                "taping": that.data.contentData.taping,
                "record_time": that.data.contentData.taping_time,
                "red_packet": that.data.contentData.red_packet,
                "red_message": that.data.contentData.red_message,
                "message": that.data.contentData.message,
                "photo": that.data.contentData.photo,
                "impression": that.data.contentData.impression,
                'type': that.data.type,
                "red_type": '0' //初始为未领取
              },
              success(res) {
                if (res.data.status == '200') {
                  wx.hideLoading()
                  wx.showToast({
                    title: '留言成功',
                    duration: 2000,
                    mask: true,
                    success: function () {
                      setTimeout(() => {
                        var pages = getCurrentPages()
                        var beforePage = pages[pages.length - 3]
                        beforePage.setData({
                          receiveIndex: 0,
                          page: 1,
                        })
                        wx.navigateBack({
                          delta: 2
                        })
                      }, 2000);
                    },
                  })
                } else {
                  console.log("留言失败:", res)
                }
              }
            })
          } else {
            wx.showModal({
              title: '您输入的内容属于敏感词汇',
              content: '请重新输入哦~',
              showCancel: false,
              mask: true,
              success(res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            })
          }
        }
      })
    })
  },
  onUnload: function () {
    this.stopVideo()
    this.setData({
      start_video: false
    })
  }
})